package httpproxymiddleware

import (
	"errors"
	"go-gateway-learn/dao"
	"go-gateway-learn/middleware"
	"go-gateway-learn/public"

	"github.com/gin-gonic/gin"
)

func HTTPFlowCountMiddleware() gin.HandlerFunc{
	return func (c *gin.Context)  {
		serverInterface, ok := c.Get("service")
		if !ok{
			middleware.ResponseError(c, 2001, errors.New("service not found"))
			c.Abort()
			return
		}
		serviceDetail := serverInterface.(*dao.ServiceDetail)
		totalCounter, err := public.FlowCounterHandler.GetCounter(public.FlowTotal)
		if err != nil{
			middleware.ResponseError(c, 4001, err)
			c.Abort()
			return
		}
		totalCounter.Increase()

		serviceCount, err := public.FlowCounterHandler.GetCounter(public.FlowServicePrefix+serviceDetail.Info.ServiceName)
		if err != nil{
			middleware.ResponseError(c, 4002, err)
			c.Abort()
			return
		}
		serviceCount.Increase()

		
		c.Next()
	}
}